//
//  WNGAddViewController.swift
//  mggz
//
//  Created by QinWei on 2018/1/17.
//  Copyright © 2018年 爱丽丝的梦境. All rights reserved.
//

import UIKit
import SnapKit
import Moya
import ObjectMapper
import RxCocoa
import RxSwift
import SVProgressHUD

class WNGAddViewController: UIViewController {
    
    //@IBOutlet weak var workerAddButton: UIButton!
    
    @IBOutlet weak var listviewBottom: NSLayoutConstraint!
    @IBOutlet weak var listview: UITableView!
    @IBOutlet weak var projectName: UILabel!
    @IBOutlet weak var moveoutView: UIView!
    @IBOutlet weak var namelayout: UIView!
    @IBOutlet weak var bottomlayout: UIView!
    
    @IBOutlet weak var bottomContent: NSLayoutConstraint!
    @IBOutlet weak var classSetView: UIView!
    var dialog:CustomDialog?
    lazy var ycDialog:CustomDialog = {
        var view = CustomDialog(frame: CGRect.zero, _title: "提示", _status: "确定要移除这些民工吗？", _submitclick: {
            self.ycDialog.dismiss()
            self.moveOperate()
        })
        
        return view
    }()
    lazy var membersArray : [WNGMemberModel] = [WNGMemberModel]()
    lazy var membersSelectArray : [String] = [String]()
    
    var selectArray:[ADDBZItem] = [ADDBZItem]()
    let disposeBag = DisposeBag()
    
    var groupId:String?
    
    lazy var selectImpl:SelectTableView = {
        var impl = SelectTableView()
        return impl
    }()
    
    
    lazy var selectTable:UITableView = {
        var view = UITableView(frame: CGRect.zero)
        view.estimatedRowHeight = 20
        view.register(UINib(nibName: "SelectCellTableViewCell", bundle: nil), forCellReuseIdentifier: "cell")
        view.separatorStyle = .singleLine
        view.rowHeight = UITableViewAutomaticDimension
        view.bounces = false
        view.tableFooterView = UIView(frame: CGRect.zero)
        view.dataSource = self.selectImpl
        view.delegate = self.selectImpl
        return view
    }()
    var currentProject: LCProjectListModel? {
        willSet {
            self.currentProject = newValue
        }
    }
    var markArray = [String]()
    var isAddSelect:Bool? = false
    fileprivate lazy var workerAddButton:UIButton = {
        let workerAddButton = UIButton.init(type: UIButtonType.custom)
        workerAddButton.setImage(UIImage.init(named: "addteam"), for: UIControlState.normal)
        //workerAddButton.frame = CGRect(x: (SCREEN_WIDTH-40)/2, y: SCREEN_HEIGHT-70, width: 40, height: 40)
        return workerAddButton
    }()
    
    lazy var currentController:UIViewController? = {
        var result:UIViewController?
        var win = UIApplication.shared.delegate?.window
        
        if win!?.windowLevel != UIWindowLevelNormal{
            var array = UIApplication.shared.windows
            for item in array{
                if item.windowLevel == UIWindowLevelNormal{
                    win = item
                    break
                }
            }
        }
        var frontView = win!?.subviews.first
        var nestResponder = frontView?.next
        if nestResponder is UIViewController{
            result = nestResponder as! UIViewController
        }else{
            result = win!?.rootViewController
        }
        return result
    }()
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        WWProgressHUD.dismiss()
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.setupWNGData()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "项目民工"
        self.projectName.text = self.currentProject?.ProjectName
        self.setupWNGData()
        //self.view.addSubview(self.tableView)
        self.view.bringSubview(toFront: self.bottomlayout)
        SVProgressHUD.setMaximumDismissTimeInterval(2)
        
        self.bottomContent.constant = -70
        
        self.workerAddButton.addTarget(self, action: #selector(workerAddClick(_:)), for: .touchUpInside)
        self.view.addSubview(self.workerAddButton)
        self.setupNavBar()
        let moveOutTap = UITapGestureRecognizer.init(target: self, action: #selector(moveoutClick(_:)))
        moveoutView.addGestureRecognizer(moveOutTap)
        let clasSetTap = UITapGestureRecognizer.init(target: self, action: #selector(classSetClick(_:)))
        classSetView.addGestureRecognizer(clasSetTap)
        
        self.listview.delegate = self
        self.listview.dataSource = self
        self.listview.bounces = false
        self.listview.separatorInset = UIEdgeInsetsMake(0, 10, 0, 10)
        self.listview.separatorInset = UIEdgeInsets.zero
        self.listview.separatorStyle = .singleLine
        self.listview.separatorColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        self.listview.backgroundColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        view.backgroundColor = UIColor.init(red: 233/255.0, green: 233/255.0, blue: 233/255.0, alpha: 1)
        self.listview.register(UINib.init(nibName: "WNGAddCell", bundle: nil), forCellReuseIdentifier: "add")
        
        
        self.dialog = CustomDialog(frame: CGRect.zero, _title: "选择班组", _customview: self.selectTable, _customHeight: 150,_widthmultipliedBy:0.8, _submitclick: {
            print("提交")
            
            guard self.selectImpl.groupId != nil && self.selectImpl.groupId != "" else{
                QWTextonlyHud("请先选择一个班组", target: self.dialog!)
                //LCProgressHUD.instance.showTextWithDiss("请先选择一个班组", target: self.dialog!)
                return
            }
            QWTextWithStatusHud("正在处理...", target: self.dialog!)
            //SVProgressHUD.show(withStatus: "正在处理")
            
            var params:[String:Any] = ["workGroupId":self.selectImpl.groupId ?? "","DemandBaseMigrantWorkerIDList":self.membersSelectArray]
            
            MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .SETWORKER, params: &params, type: AddGroup.self, success: { (bean,_) in
                QWHudDiss(self.dialog!)
                //SVProgressHUD.dismiss(withDelay: 0.4)
                if var b = bean as? AddGroup {
                    if b.State == "OK"{
                        self.setupWNGData()
                        self.dialog?.dismiss()
                        QWTextonlyHud("操作成功", target: self.view)
                    }else{
                        self.dialog?.dismiss()
                        QWTextonlyHud(b.State, target: self.view)
                        
                    }
                }
            }, error: { (error) in
                QWHudDiss(self.dialog!)
                switch error{
                case .HTTPERROR:
                    QWTextonlyHud("网络异常", target: self.dialog!)
                    break;
                case .DATAFAIL:
                    QWTextonlyHud("数据异常", target: self.dialog!)
                    break;
                case .DATAERROR:
                    QWTextonlyHud("数据异常", target: self.dialog!)
                    break;
                case .StateFail(let obj):
                    guard let data = obj as? [String:Any] else{
                        QWTextonlyHud("数据异常", target: self.dialog!)
                        return
                    }
                    QWTextonlyHud(data["Msg"] as? String ?? "", target: self.dialog!)
                    break
                }
            })
        })
        
        /*self.dialog = CustomDialog(frame: CGRect.zero, _title: "选择班组", _status: "content", _submitclick: {
            print("提交")
        })*/
        
    }
    
    
    override func viewDidLayoutSubviews() {
        
        self.workerAddButton.snp.updateConstraints { (make) in
            make.width.height.equalTo(40)
            make.centerX.equalTo(self.view)
            make.bottom.equalTo(self.bottomlayout.snp.top).offset(-10)
        }
    }
    
    func moveOperate(){
        QWTextWithStatusHud("正在移除...", target: self.view)
        let accountId = WWUser.sharedInstance.accountId ?? ""
        LCAPiMainManager.request(.RemoveOnlineWorker(DemandBaseMigrantWorkerIDList: self.membersSelectArray, AccountId: accountId)) { (result) in
            QWHudDiss(self.view)
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{
                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    QWTextonlyHud(jsonString["Msg"] as? String ?? "数据异常", target: self.view)
                    return
                }
                QWTextonlyHud("移除成功!", target: self.view)
                self.membersSelectArray.removeAll()
                self.setupWNGData()
                
                //WWProgressHUD.success("移除成功!")
            }
        }
    }
    
    @objc fileprivate func moveoutClick(_ tap : UITapGestureRecognizer){
    
        //WWProgressHUD.showWithStatus("")
        
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
        guard self.membersSelectArray.count>0 else {
            //WWProgressHUD.error("未选中目标!")
            QWHudDiss(self.view)
            QWTextonlyHud("请先选择人员", target: self.view)
            return
        }
        self.ycDialog.show()
        
    
        
        
    }
    
    
    func show() {
        self.selectImpl.groupId = ""
        self.dialog?.show()
    }
    @objc fileprivate func classSetClick(_ tap : UITapGestureRecognizer){
        
        if self.membersSelectArray.count == 0{
            QWTextonlyHud("请先选择人员", target: self.view)
        }else{
            
            var params:[String:Any] = ["MarketSupplyBaseID":(currentProject?.MarketSupplyBaseID)!]
            MNetHttp.sharedInstance.postSingle(API_CALL_METHOD, method: .ADDBZ, params: &params, type: ADDBZ.self, success: { (bean,_) in
                guard let data = bean as? ADDBZ else{
                    
                    return
                }
                
                if data.Result?.count ?? 0 > 0{
                    self.selectArray.removeAll()
                    self.selectArray.append(contentsOf: data.Result!)
                    self.selectImpl.selectArray = self.selectArray
                    self.selectTable.reloadData()
                    self.show()
                }else{
                    QWTextonlyHud("请先添加班组", target: self.view)
                }
            }) { (error) in
                switch error{
                case .DATAERROR:
                    break
                case .DATAFAIL:
                    break
                case .HTTPERROR:
                    break
                case .StateFail(let obj):
                    guard let data = obj as? [String:Any] else{
                        QWTextonlyHud("数据异常", target: self.dialog!)
                        return
                    }
                    QWTextonlyHud(data["Msg"] as? String ?? "", target: self.dialog!)
                }
            }
        }
        
        
        
    }
    
    fileprivate func setupNavBar(){
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "多选", fontSize: 17, self, #selector(addChooseClick))
    }
    @objc fileprivate func addChooseClick(){
        if isAddSelect == false {
            
            self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", fontSize: 17, self, #selector(addChooseClick))
            isAddSelect = true
            self.bottomContent.constant = 0
            self.listviewBottom.constant = 70
            
            UIView.animate(withDuration: 0.4, animations: {
                self.workerAddButton.alpha = 0
                
                
                self.view.layoutIfNeeded()
            }, completion: { (flag) in
                if flag{
                    self.workerAddButton.isEnabled = false
                    
                }
            })
        }else{
            isAddSelect = false
            self.membersSelectArray.removeAll()
            self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "多选", fontSize: 17, self, #selector(addChooseClick))
            
            self.markArray.enumerated().forEach({ (position,item) in
                if item == "1"{
                    self.markArray.replaceSubrange(position..<(position+1), with: ["0"])
                }
            })
            //self.tableView.reloadData()
            self.bottomContent.constant = -70
            self.listviewBottom.constant = 0
            UIView.animate(withDuration: 0.4, animations: {
                
                self.workerAddButton.alpha = 1
                
                self.view.layoutIfNeeded()
            }, completion: { (flag) in
                if flag{
                    self.workerAddButton.isEnabled = true
                    
                    self.listview.reloadData()
                }
            })
        }
        
    }
    
    @objc fileprivate func workerAddClick(_ sender: UIButton) {
        let otherAdd = WNGOtherViewController(nibName: "WNGOtherViewController", bundle: nil)
        otherAdd.currentProject = currentProject
        self.navigationController?.pushViewController(otherAdd, animated: true)
    }
    
    fileprivate func setupWNGData(){
        guard let accountId = WWUser.sharedInstance.accountId else{
            return
        }
    LCAPiMainManager.request(.GetOnlineWorker(MarketSupplyBaseID: (currentProject?.MarketSupplyBaseID)!, pageIndex: 1, pageSize: 25, AccountId: accountId)) { (result) in
            if case let .success(response) = result {
                guard  let jsonString :NSDictionary = try?response.mapJSON() as! NSDictionary else{

                    return
                }
                guard (jsonString["State"]) as! String == "OK" else{
                    return
                }
                guard let resultDic = jsonString["Result"] as? [String: AnyObject] else{
                    return
                }
                guard let itemsArray = resultDic["Items"] as? NSArray else{
                    return
                }
                print(jsonString)
                self.membersArray = Mapper<WNGMemberModel>().mapArray(JSONObject: itemsArray)!
                print(self.membersArray)
                self.listview.reloadData()
                self.markArray.removeAll()
                self.membersArray.forEach({ (item) in
                    self.markArray.append("0")
                })
            }
        }
    }
    
}

class SelectTableView:NSObject,UITableViewDelegate,UITableViewDataSource{
    var _selectArray:[ADDBZItem]?
    var groupId:String?
    
    var selectArray:[ADDBZItem]?{
        get{
            return self._selectArray
        }
        set(newValue){
            self._selectArray = newValue!
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.selectArray?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: IndexPath(item: indexPath.row, section: 0)) as? SelectCellTableViewCell
        if cell == nil{
            cell = SelectCellTableViewCell(style: .default, reuseIdentifier: "cell")
        }
        cell?.selectedBackgroundView?.backgroundColor = UIColor.white
        cell?.data = self.selectArray![indexPath.row]
        return cell!
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("--\(indexPath.row)")
        self.groupId = self.selectArray![indexPath.row].ID ?? ""
        
        
    }
    
    
}

extension WNGAddViewController : UITableViewDelegate,UITableViewDataSource{
    
    @objc func telClick(_ sender:UIButton){
        print("tell--->\(sender.tag ?? 0)")
        guard let telnum = self.membersArray[sender.tag ?? 0].CellPhone else{
            return
        }
        UIApplication.shared.openURL(URL(string: "telprompt:\(telnum)")!)
        
    }
    
    func sendtoDetail(_ index:Int){
        let mwDetail = MWDetailInfoViewController(nibName: "MWDetailInfoViewController", bundle: nil)
        mwDetail.reFreshData = {(value) in
            if value == true {
                //self.setupMWLocationData()
                self.setupWNGData()
            }
        }
        mwDetail.DemandBaseMigrantWorkerID = self.membersArray[index].DemandBaseMigrantWorkerID ?? ""
        mwDetail.currentProjectName = ProjectName
        mwDetail.currentProjectId = ProjectId
        mwDetail.isZG = true
        mwDetail.LocateTime = ""//"2018-12-12"
        //mwDetail.currentProject = selectedProject
        self.navigationController?.pushViewController(mwDetail, animated: true)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.membersArray.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell : WNGAddCell = tableView.dequeueReusableCell(withIdentifier: "add") as! WNGAddCell
 cell.setupWmgModelDataWith(self.membersArray[indexPath.row])
        cell.classLabel.isHidden = true
        cell.tellbtn.tag = indexPath.row
        cell.tellbtn.addTarget(self, action: #selector(telClick(_:)), for: .touchUpInside)
        let markStr = self.markArray[indexPath.row]
        if markStr == "0" {
            cell.dagouView.isHidden = true
        }else if markStr == "1" {
            cell.dagouView.isHidden = false
        }
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selectModel : WNGMemberModel = self.membersArray[indexPath.row]
        if isAddSelect == true{
            let markStr = self.markArray[indexPath.row]
            if markStr == "0"{
                self.markArray.replaceSubrange(indexPath.row..<(indexPath.row+1), with: ["1"])
                //self.markArray?.replaceObject(at: indexPath.row, with: "1")
                self.membersSelectArray.append(selectModel.DemandBaseMigrantWorkerID!)
            }else if markStr == "1"{
                self.markArray.replaceSubrange(indexPath.row..<(indexPath.row+1), with: ["0"])
                var i = self.membersSelectArray.count
                self.membersSelectArray.reversed().forEach({ (item) in
                    i -= 1
                    if item == selectModel.DemandBaseMigrantWorkerID{
                        self.membersSelectArray.remove(at: i)
                    }
                })
            }
            self.listview.reloadData()
        }else{
            self.sendtoDetail(indexPath.row)
        }
        
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
}
